/**
 * 
 */
package com.yi.backend.model.api.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.yi.backend.db.api.IMongoDBHelperApi;
import com.yi.backend.db.api.impl.MongoDBConstants;
import com.yi.backend.model.CommonModel;
import com.yi.backend.model.api.ICommonModelApi;


/**
 * @author long
 *
 */
public class MongoCommonModelApi implements ICommonModelApi{
	

	public CommonModel convertEntityToCommonModel(DBObject entity){
		CommonModel model = new CommonModel();
		if(entity.get(MongoDBConstants.idCol) != null) model.id = entity.get(MongoDBConstants.idCol).toString();
		if(entity.get(MongoDBConstants.nameCol) != null) model.name = entity.get(MongoDBConstants.nameCol).toString();
		if(entity.get(MongoDBConstants.descCol) != null) model.desc = entity.get(MongoDBConstants.descCol).toString();
		if(entity.get(MongoDBConstants.createdCol) != null) model.created = entity.get(MongoDBConstants.createdCol).toString();
		if(entity.get(MongoDBConstants.updatedCol) != null) model.updated = entity.get(MongoDBConstants.updatedCol).toString();
		return model;
	}
	
	public DBObject convertCommonModelToEntity(CommonModel model){
		DBObject entity = new BasicDBObject();
		if(StringUtils.hasLength(model.id))  entity.put(MongoDBConstants.idCol, model.id);
		if(StringUtils.hasLength(model.name))  entity.put(MongoDBConstants.nameCol, model.name);
		if(StringUtils.hasLength(model.desc))  entity.put(MongoDBConstants.descCol, model.desc);
		try {
			if(StringUtils.hasLength(model.created))
				entity.put(MongoDBConstants.createdCol, new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm:ss").parse(model.created));
			else
				entity.put(MongoDBConstants.createdCol, new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm:ss").format(new Date()));
			
			if(StringUtils.hasLength(model.updated))
				entity.put(MongoDBConstants.updatedCol, new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm:ss").parse(model.updated));
			else
				entity.put(MongoDBConstants.updatedCol, new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm:ss").format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return entity;
	}
	
	

}
